<template>
  <a-table :columns="columns" :data-source="data" />
  <a-table class="trColor" style="width: 100%;" :pagination="false"
    :row-class-name="(_record) => (_record.children ? `${_record.basicName}BgColor` : undefined)" :columns="yearColumns"
    :data-source="testData">
    <template #bodyCell="{ column, text, record }">
      <!-- <span>{{ column.dataIndex }}</span> -->
      <!-- <a-input v-model:value=""></a-input> -->

      <a-input v-if="editableData[record.basicName]&&column.dataIndex!='name'&&column.dataIndex!='total'&&column.dataIndex!='operation'" v-model:value="editableData[record.basicName][column.dataIndex]"
        style="margin: -5px 0"></a-input>
      <template v-else>
        <!-- {{ `测试` + column.dataIndex }} -->
        <span>{{ column.dataIndex == 'total' && record.total == -1 ? '-' : text }}</span>
        <!-- <span>{{ column.dataIndex == 'total'? '8' : text }}</span> -->
        <span v-if="record.total == -1 && column.dataIndex !== 'name' && column.dataIndex !== 'total'">%</span>
      </template>

      <template v-if="column.dataIndex === 'operation'">
        <div class="editable-row-operations">
          <span v-if="editableData[record.basicName]">
            <a-typography-link @click="save(record.basicName)">Save</a-typography-link>
            <a-popconfirm title="Sure to cancel?" @confirm="cancel(record.basicName)">
              <a>Cancel</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="edit(record.basicName)">Edit</a>
          </span>
        </div>
      </template>
    </template>
  </a-table>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { number, string } from 'vue-types';
import type { UnwrapRef } from 'vue';
import { cloneDeep } from 'lodash';
// import { cloneDeep, forIn } from 'lodash';

const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: 'Age',
    dataIndex: 'age',
    key: 'age',
    width: '12%',
  },
  {
    title: 'Address',
    dataIndex: 'address',
    width: '30%',
    key: 'address',
  },
]
interface DataItem {
  key: number;
  name: string;
  age?: number;
  address?: string;
  children?: DataItem[];
}

const data: DataItem[] = [
  {
    key: 1,
    name: 'John Brown sr.',
    age: 60,
    address: 'New York No. 1 Lake Park',
    children: [
      {
        key: 11,
        name: 'John Brown',
        age: 42,
        address: 'New York No. 2 Lake Park',
      },
      {
        key: 12,
        name: 'John Brown jr.',
        age: 30,
        address: 'New York No. 3 Lake Park',
        children: [
          {
            key: 121,
            name: 'Jimmy Brown',
            age: 16,
            address: 'New York No. 3 Lake Park',
          },
        ],
      },
      {
        key: 13,
        name: 'Jim Green sr.',
        age: 72,
        address: 'London No. 1 Lake Park',
        children: [
          {
            key: 131,
            name: 'Jim Green',
            age: 42,
            address: 'London No. 2 Lake Park',
            children: [
              {
                key: 1311,
                name: 'Jim Green jr.',
                age: 25,
                address: 'London No. 3 Lake Park',
              },
              {
                key: 1312,
                name: 'Jimmy Green sr.',
                age: 18,
                address: 'London No. 4 Lake Park',
              },
            ],
          },
        ],
      },
    ],
  },
  {
    key: 2,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
];
interface BCSModel {

}

const editableData: UnwrapRef<Record<string, any>> = reactive({});

const edit = (basicName: string) => {
  console.log('行号', basicName);

  for (const item of testData.value) {
    if (item.children && item.children.length > 0) {
      for (const smallItem of item.children) {
        if (smallItem.basicName === basicName) {
          // console.log('找到了',smallItem);
          editableData[basicName] = cloneDeep(smallItem)
          break;
        }
      }
      // console.log('继续');
      if (editableData[basicName]) {
        break
      }
    }
  }

};
const save = (basicName: string) => {
  // 寻找到testData中对应的对象，然后进行赋值操作
  for (const item of testData.value) {
    if (item.children && item.children.length > 0) {
      for (let smallItem of item.children) {
        console.log('testoooo',basicName,smallItem);
        
        if (smallItem.basicName === basicName) {
          // console.log('找到了',smallItem);
          // editableData[basicName]=cloneDeep(smallItem)
          // smallItem = cloneDeep(editableData[basicName])
          Object.assign(smallItem,editableData[basicName])
          console.log('测试成没成',smallItem);
          delete editableData[basicName];
          break;
        }
      }
      // console.log('继续');
      if (!editableData[basicName]) {
        break
      }
    }
  }


  // Object.assign(testData.value.filter(item => basicName == item.basicName)[0], editableData[basicName]);
  
};

const cancel = (basicName: string) => {
  delete editableData[basicName];
};

// 需要的数据
let str = '{"year_total":[2019,2021,2022,2023],"income":{"car_output_rfq":[10000,10000,10000,10000,40000],"ir_rate_rfq":[83.5,83.5,83.5,83.5,-1],"ir_number_rfq":[8350,8350,8350,8350,33400],"car_output":[9000,9000,9000,9000,36000],"ir_rate":[83.5,83.5,83.5,83.5,-1],"ir_number":[7515,7515,7515,7515,30060],"hardware_price":[{"Price":8500,"Percent":100},{"Price":0,"Percent":100},{"Price":4000,"Percent":100},{"Price":9898,"Percent":100},{"Price":-1,"Percent":-1}],"software_price":[{"Price":0,"Percent":100},{"Price":3400,"Percent":100},{"Price":660.2475,"Percent":100},{"Price":0,"Percent":100},{"Price":-1,"Percent":-1}],"develop_one":[0,0,0,0,0],"software_service":[0,0,0,0,0],"hardware_income":[63877500,0,30060000,74383470,168320970],"software_income":[0,25551000,4961759.962499999,0,30512759.9625]},"three_cost":{"hardware_buy_price":[{"Price":0,"Percent":100},{"Price":0,"Percent":100},{"Price":0,"Percent":100},{"Price":0,"Percent":100},{"Price":-1,"Percent":-1}],"all_buy_cost":[0,0,0,0,0],"supply_developer_money":[0,0,0,0,0],"three_all_cost":[0,0,0,0,0]},"in_platform":{"ark_sw":[0,0,0,0,0],"ark_develop":[0,0,0,0,0],"software_tools":[{"Price":0,"IrNumber":7515},{"Price":0,"IrNumber":7515},{"Price":0,"IrNumber":7515},{"Price":0,"IrNumber":7515},{"Price":0,"IrNumber":0}],"ark_hardware_develop":[0,0,0,0,0],"drive_platform_price":[156,156,156,156,624],"stop_platform_price":[54,54,54,54,216],"base_drive_price":[7.1,7.1,7.1,7.1,28.4],"other_func":[0,0,0,0,0],"software_platform_dev":[1631506.5,1631506.5,1631506.5,1631506.5,6526026]},"cus_cost":{"develop_people_cost":[0,0,0,0,0],"develop_no_people_cost":[0,0,0,0,0],"cus_project_dev_cost":[0,0,0,0,0]},"over_head":{"period_fee":[0,0,0,0,0]},"over_view":{"all_sales_income":[63877500,25551000,35021759.9625,74383470,198833729.9625],"all_develop_fee":[1631506.5,1631506.5,1631506.5,1631506.5,6526026],"all_cost":[0,0,0,0,0],"tax_profit":[0,0,0,0,0],"tax_profit_percent":[0,0,0,0,-1]}}'



// 转换为对象的数据
let strObjData = JSON.parse(str)
// console.log(strObjData);

interface BcsDetailIncomeModel {
  car_output: number[],
  car_output_rfq: number[],
  develop_one: number[],
  hardware_income: number[],
  hardware_price: number[],// 两个待定
  software_price: number[],
  ir_number: number[],
  ir_number_rfq: number[],
  ir_rate: number[],
  ir_rate_rfq: number[],
  software_service: number[],
}
interface BcsDetailThreeCostModel {
  all_buy_cost: number[],
  hardware_buy_price: number[],  //待定
  supply_developer_money: number[],
  three_all_cost: number[]
}
interface BcsDetailInPlatformModel {
  ark_develop: number[],
  ark_hardware_develop: number[],
  supply_developer_money: number[],
  ark_sw: number[]
  base_drive_price: number[]
  drive_platform_price: number[],
  other_func: number[],
  software_platform_dev: number[],
  software_tools: number[],  // 待定
  stop_platform_price: number[],
}
interface BcsDetailCusCostModel {
  cus_project_dev_cost: number[],
  develop_no_people_cost: number[],
  develop_people_cost: number[],
}
interface BcsDetailOverViewModel {
  all_cost: number[],
  all_develop_fee: number[],
  all_sales_income: number[],
  tax_profit: number[],
  tax_profit_percent: number[],
}


// 为转换完成的数据定义数据类型的接口
interface BcsDetailTableDataModel {
  year_total: number[],
  income: BcsDetailIncomeModel,
  three_cost: BcsDetailThreeCostModel,
  in_platform: BcsDetailInPlatformModel,
  cus_cost: BcsDetailCusCostModel,
  over_head: { period_fee: number[] },
  over_view: BcsDetailOverViewModel

}

// 得到内部年份进行处理，处理成表头的格式
let yearColumns = reactive<{ title: string, dataIndex: string, key: string, fixed: boolean, align: string }[]>([])

// yearColumns = strObjData.year_total.map((item: number) => {
//   let newItem = {
//     title: item.toString(), dataIndex: 'zhaoTest' + item.toString(), key: item.toString(), fixed: false
//   }
//   return newItem
// })
// yearColumns.unshift({ title: '费用类型', dataIndex: 'name', key: '-1', fixed: false })
// yearColumns.push({ title: '总计', dataIndex: 'total', key: '-2', fixed: false })
// console.log(yearColumns);
let index = ref(1)
let testData = ref<{
  key: number,
  name: string,
  children?: Array<any>
}[]>([])



// 定义一个函数用于处理BCS详情页面当中表格数据中的名字显示
const dealNameDataShow = (name: string) => {
  switch (name) {
    // 收入端部分
    case 'income':
      return '收入端'
    case 'car_output_rfq':
      return '车型产量(RFQ)'
    case 'ir_rate_rfq':
      return '搭载率(RFQ)'
    case 'car_output':
      return '车型产量'
    case 'ir_number_rfq':
      return '搭载量(RFQ)'
    case 'car_output':
      return '车型产量(调整)'
    case 'ir_rate':
      return '搭载率(调整)'
    case 'ir_number':
      return '搭载量(调整)'
    case 'hardware_price':
      return '硬件单价'
    case 'software_price':
      return '软件授权单价'
    case 'develop_one':
      return '开发费一次性补偿'
    case 'software_service':
      return '软件服务费'
    case 'hardware_income':
      return '硬件收入'
    case 'software_income':
      return '软件授权收入'

    // 第三方成本部分
    case 'three_cost':
      return '第三方成本'
    case 'hardware_buy_price':
      return '硬件采购单价'
    case 'all_buy_cost':
      return '总硬件采购成本'
    case 'supply_developer_money':
      return '供应商开发费'
    case 'three_all_cost':
      return '第三方总成本'

    // 内部平台部分 
    case 'in_platform':
      return '内部平台'
    case 'ark_sw':
      return 'ARK SW工具链分摊'
    case 'ark_develop':
      return 'ARK研发人员分摊'
    case 'software_tools':
      return '软件工具授权费'
    case 'ark_hardware_develop':
      return 'ARK硬件平台开发平摊费'
    case 'drive_platform_price':
      return '行车平台软件分摊单价'
    case 'stop_platform_price':
      return '泊车平台软件分摊单价'
    case 'base_drive_price':
      return '基础行车功能分摊单价'
    case 'other_func':
      return '其他功能分摊'
    case 'software_platform_dev':
      return '软件平台开发分摊费'

    // 客户项目研发成本部分
    case 'cus_cost':
      return '客户项目研发成本'
    case 'develop_people_cost':
      return '研发人力成本'
    case 'develop_no_people_cost':
      return '研发非人力成本'
    case 'cus_project_dev_cost':
      return '客户项目研发成本'

    // 期间成本部分
    case 'over_head':
      return '期间成本'
    case 'period_fee':
      return '期间费用'

    // 核算总览部分
    case 'over_view':
      return '核算总览'
    case 'all_develop_fee':
      return '总研发费用'
    case 'all_sales_income':
      return '总销售收入'
    case 'all_cost':
      return '总成本'
    case 'tax_profit':
      return '息税前利润'
    case 'tax_profit_percent':
      return '息税前利润百分比'
    default:
      return '未知'
  }
}

// 处理其他的大部分数据
const dealDataTest = (listData: any, bcsId: string) => {

  let tableColumns: {
    title: string, dataIndex: string, key: string, fixed: boolean, align: string
  }[] = []
  /**
   * 处理表头数据
   */
  tableColumns = listData.year_total.map((item: number) => {
    let newItem = {
      title: item.toString(), dataIndex: bcsId + item.toString(), key: item.toString(), fixed: false, align: 'center'
    }
    return newItem
  })
  tableColumns.unshift({ title: '费用类型', dataIndex: 'name', key: '-1', fixed: false, align: 'left' })
  tableColumns.push({ title: '总计', dataIndex: 'total', key: '-2', fixed: false, align: 'center' })
  tableColumns.push({ title: '操作', dataIndex: 'operation', key: '-3', fixed: false, align: 'center' })

  /**
   * 下边处理的是表格提数据
   */
  // 处理数据，
  let firstArr = []
  // 遍历的是最大的对象
  for (const itemArea in listData) {
    // console.log('test', itemArea);
    if (itemArea === 'year_total') continue
    // console.log('test', itemArea);
    let secondObj: {
      key: number,
      name: string,
      basicName: string
      children: Array<any>
    } = {
      key: 1,
      name: '',
      basicName: '',
      children: []
    }
    secondObj.name = dealNameDataShow(itemArea)
    secondObj.basicName = itemArea
    secondObj.key = index.value++
    // 遍历的是每部分的那个对象，其中的每项是一个数组
    for (const smallItem in listData[itemArea]) {
      let thirdObj: {
        key: number,
        name: string,
        basicName: string

      } = {
        key: 1,
        name: '',
        basicName: '',

      }
      thirdObj.name = dealNameDataShow(smallItem)
      thirdObj.basicName = smallItem
      thirdObj.key = index.value++
      listData[itemArea][smallItem].forEach((item: any, idx: number) => {
        if (idx <= listData.year_total.length - 1) {
          // console.log(thirdObj.basicName, item);
          // if (thirdObj.basicName === 'software_tools') {
          //   Reflect.set(thirdObj, `${bcsId}${listData.year_total[idx]}`, item.Price*item.IrNumber)

          // }else{}

          if (Object.prototype.toString.call(item) === '[object Object]') {
            if (thirdObj.basicName === 'software_tools') {
              Reflect.set(thirdObj, `${bcsId}${listData.year_total[idx]}`, item.Price * item.IrNumber)
            } else {
              Reflect.set(thirdObj, `${bcsId}${listData.year_total[idx]}`, item.Price * item.Percent / 100)
            }
          } else {
            Reflect.set(thirdObj, `${bcsId}${listData.year_total[idx]}`, item)
          }
        } else {
          if (Object.prototype.toString.call(item) === '[object Object]') {
            if (thirdObj.basicName === 'software_tools') {
              Reflect.set(thirdObj, `total`, item.Price * item.IrNumber)
            } else {

              if (Object.values(item).every(itnum => itnum === -1)) {
                Reflect.set(thirdObj, `total`, '-')
              } else {
                Reflect.set(thirdObj, `total`, item.Price * item.Percent / 100)
              }
            }
          } else {
            Reflect.set(thirdObj, 'total', item)
          }
        }
      })
      secondObj.children.push(thirdObj)
    }
    firstArr.push(secondObj)
  }
  return { tableBody: firstArr, tableHeader: tableColumns }
}

onMounted(() => {
  let { tableBody, tableHeader } = dealDataTest(strObjData, 'zhaoTest')
  testData.value = tableBody
  yearColumns = tableHeader

  console.log('***//122222/***', yearColumns);
  console.log('***///***', testData.value);
})


</script>

<style lang="less" scoped>
.trColor {
  :deep(.ant-table-tbody > tr.ant-table-row:hover > td, .ant-table-tbody > tr > td.ant-table-cell-row-hover) {
    background: #E6F8F2;
  }

  :deep(.incomeBgColor) td {
    background: linear-gradient(0deg, #FFF6F5, #FFF6F5),
      linear-gradient(0deg, #FFF7F5, #FFF7F5);
  }

  :deep(.three_costBgColor) td {
    background: linear-gradient(0deg, #FFF6F5, #FFF6F5),
      linear-gradient(0deg, #FFF7F5, #FFF7F5);
  }

  :deep(.in_platformBgColor) td {
    // background-color: #F9FFFC;
    background: linear-gradient(0deg, #F0F6FF, #F0F6FF),
      linear-gradient(0deg, #F5FAFF, #F5FAFF);
  }

  :deep(.cus_costBgColor) td {
    background: linear-gradient(0deg, #FEFBE5, #FEFBE5),
      linear-gradient(0deg, #FFFDEE, #FFFDEE);
  }

  :deep(.over_headBgColor) td {
    background: linear-gradient(0deg, #FAF4FF, #FAF4FF),
      linear-gradient(0deg, #FCF9FF, #FCF9FF);
  }

  :deep(.over_viewBgColor) td {
    background: linear-gradient(0deg, #E4E8FF, #E4E8FF),
      linear-gradient(0deg, #F0F2FF, #F0F2FF);
  }
}
</style>

